package cn.gson.oasys.controller.login;

import cn.gson.oasys.model.entity.user.LoginRecord;
import cn.gson.oasys.model.entity.user.User;
import cn.gson.oasys.services.user.UserLoginRecordService;
import cn.gson.oasys.services.user.UserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Objects;
import java.util.Random;



@Api(value = "登录Controller")
@Controller
@RequestMapping("/")
public class LoginsController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserService userService;

	@Autowired
	private UserLoginRecordService userLoginRecordService;

	public static final String CAPTCHA_KEY = "session_captcha";

	private Random rnd = new Random();

	@ApiOperation(value = "登录界面的显示")
	@GetMapping(value="logins")
	public String login(){
		return "login/login";
	}

	@ApiOperation(value = "用户退出系统")
	@RequestMapping("loginout")
	public String loginout(HttpSession session){
		session.removeAttribute("userId");
		return "redirect:/logins";
	}
	
	/**
	 * 登录检查；
	 * 1、根据(用户名或电话号码)+密码进行查找
	 * 2、判断使用是否被冻结；
	 * @return
	 * @throws UnknownHostException 
	 */
	@ApiOperation(value = "登录检查")
	@PostMapping(value = "logins")
	public String loginCheck(HttpSession session, HttpServletRequest  request, Model model) throws UnknownHostException{

		//从请求request中获取登录信息
		String userName=request.getParameter("userName").trim();
		String password=request.getParameter("password");
		String code=request.getParameter("code").toLowerCase();

		//验证用户名是否合法
		if (!StringUtils.isNotBlank(userName)) {
			model.addAttribute("errormess", "用户名不能为空！");
			request.setAttribute("errormess","用户名不能为空！");
			return "login/login";
		}

		//验证密码是否合法
		if (!StringUtils.isNotBlank(password)) {
			model.addAttribute("errormess", "密码不能为空！");
			request.setAttribute("errormess","密码不能为空");
			return "login/login";
		}

		model.addAttribute("userName", userName);

		//从session中获取验证码
		String sesionCode = (String) request.getSession().getAttribute(CAPTCHA_KEY);

		if(!code.equals(sesionCode.toLowerCase())){
			model.addAttribute("errormess", "验证码输入错误!");
			request.setAttribute("errormess","验证码输入错误!");
			return "login/login";
		}

		//将用户名分开查找；用户名或者电话号码
		User user = userService.getUserByNameAndPwd(userName, password);

		if(Objects.isNull(user)){
			model.addAttribute("errormess", "账号或密码错误!");
			return "login/login";
		}
		//是否被锁
		if(user.getIsLock() == 1){
			model.addAttribute("errormess", "账号已被冻结!");
			return "login/login";
		}

		Object sessionId=session.getAttribute("userId");
		//判断当前用户是否已经登录
		if(sessionId==user.getUserId()){
			model.addAttribute("hasmess", "当前用户已经登录了；不能重复登录");
			session.setAttribute("thisuser", user);
			return "login/login";
		}else{
			session.setAttribute("userId", user.getUserId());
			Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
			Version version = browser.getVersion(request.getHeader("User-Agent"));
			String info = browser.getName() + "/" + version.getVersion();
			String ip=InetAddress.getLocalHost().getHostAddress();
			//新增登录记录
			userLoginRecordService.save(new LoginRecord(ip, new Date(), info, user));
		}
		return "redirect:/index";
	}
	
	@RequestMapping("handlehas")
	public String handleHas(HttpSession session){

		if(!StringUtils.isEmpty(session.getAttribute("thisuser")+"")){
			User user=(User) session.getAttribute("thisuser");
			System.out.println(user);
			session.removeAttribute("userId");
			session.setAttribute("userId", user.getUserId());
		}else{
			System.out.println("有问题！");
			return "login/login";
		}
		return "redirect:/index";
	}

	@ApiOperation(value = "生成验证码并显示")
	@RequestMapping("captcha")
	public void captcha(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException{

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		
		// 生成图片
		int w = 135, h = 40;
		VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

		// 将验证码存储在session以便登录时校验
		session.setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());
	}
}
